package thread;
//当多个线程并发操作同一个临界资源，由于线程切换不确定，导致操作顺序混乱从而引发各种不良后果
//这个现象称为多线程并发安全问题
//临界资源，同一时刻只能是被单一线程操作的资源
public class SyncDemo {
    static boolean zhangsan = false;
    static boolean lisi = false;
    public static void main(String[] args) {
        Bank bank = new Bank();
        while (true) {
            Thread t1 = new Thread("张三") {
                public void run() {
                    zhangsan = bank.getMoney(20000);
                }
            };
            Thread t2 = new Thread() {
                @Override
                public void run() {
                    lisi = bank.getMoney(20000);
                }
            };
            t1.start();
            t2.start();
            try {
                Thread.sleep(10);//阻塞主线程，目的是等待t1  t2  执行完取款动作
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            //如果两个都是true则说明出现了并发安全问题
            System.out.println(zhangsan + "," + lisi);
            if (zhangsan&&lisi){
                System.out.println("出现了并发安全问题");
                break;
            }else {
                bank.setAccount(20000);
                zhangsan = false;
                lisi = false;
            }
        }
    }
}
